<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native.prevent="searchQuery1">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="选择门店" required>
              <a-cascader
                :options="departModel.departTreeOptions"
                :showSearch="true"
                expand-trigger="hover"
                placeholder=""
                :fieldNames="departModel.fieldNames"
                style="width: 190px"
                v-model="queryParam.selecteddeparts"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="会员手机">
              <a-input placeholder v-model="queryParam.mobile"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="会员姓名">
              <a-input placeholder v-model="queryParam.realName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click.prevent="searchQuery1" icon="search">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
    <!-- <a-button type="primary" icon="download" @click="handleExportXls1('日营业数据')" v-if="(dataSource && dataSource.length != 0)">导出</a-button> -->
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        v-show="isQueryed"
        summary
      >  
      <span slot="balance" slot-scope="text, record">
        <a @click="handleMemberPointsDetail(record)" v-if="text != 0">{{text}}</a>
        <span v-else>{{text}}</span>
      </span>
      <span slot="totalAmount" slot-scope="text, record">
        <a @click="handleTotalBalanceDetail(record)" v-if="text != 0">{{text}}</a>
        <span v-else>{{text}}</span>
      </span>
       <span slot="salTotalAmount" slot-scope="text, record">
        <a @click="handleExpendBalanceDetail(record)" v-if="text != 0">{{text}}</a>
        <span v-else>{{text}}</span>
      </span>
      <span slot="couponCnt" slot-scope="text, record">
        <a @click="handleMemberCouponDetail(record)" v-if="text != 0">{{text}}</a>
        <span v-else>{{text}}</span>
      </span>
      <span slot="canUseCoupon" slot-scope="text, record">
        <a @click="handleMemberunUseCouponDetail(record)" v-if="text != 0">{{text}}</a>
        <span v-else>{{text}}</span>
      </span>
      <span slot="usedCoupon" slot-scope="text, record">
        <a @click="handleMemberUsedCouponDetail(record)" v-if="text != 0">{{text}}</a>
        <span v-else>{{text}}</span>
      </span>
      <span slot="unUseCoupon" slot-scope="text, record">
        <a @click="handleMemberunUsedCouponDetail(record)" v-if="text != 0">{{text}}</a>
        <span v-else>{{text}}</span>
      </span>
      </a-table>
      <div class="ant-alert ant-alert-info" v-show="!isQueryed">请选择条件进行查询</div>
     
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <ReportMemberBalanceCntDetail ref="modelFormBalanceDetail"></ReportMemberBalanceCntDetail>
    <ReportMemberTotalBalanceDetail ref="modelFormTotalBalanceDetail"></ReportMemberTotalBalanceDetail>
    <ReportMemberExpendCntDetail ref="modelFormExpendDetail"></ReportMemberExpendCntDetail>
    <ReportMemberGrantCouponDetail ref="modelFormGrantCouponDetail"></ReportMemberGrantCouponDetail>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import moment from 'moment'
import { getAction, downFile } from '@/api/manage'
import { queryDepartTreeList1 } from '@/api/api'
import ReportMemberBalanceCntDetail from './modules/ReportMemberBalanceCntDetail'
import ReportMemberTotalBalanceDetail from './modules/ReportMemberTotalBalanceDetail'
import ReportMemberExpendCntDetail from './modules/ReportMemberExpendCntDetail'
import ReportMemberGrantCouponDetail from './modules/ReportMemberGrantCouponDetail'
export default {
  name: 'MemberReport',
  mixins: [JeecgListMixin],
  components: {
    ReportMemberBalanceCntDetail,
    ReportMemberTotalBalanceDetail,
    ReportMemberExpendCntDetail,
    ReportMemberGrantCouponDetail
  },
  data() {
    return {
      description: '会员积分报表',
      disableMixinCreated: true,
      departModel: {
        departTreeOptions: [],
        fieldNames: { label: 'title', value: 'value', children: 'children' }
      },
      //这个汇总变量,元素改成下面方法定义的
      sumModel: {
        departName: '',
        realName: '',
        mobile: '',
        balance: 0,
        totalAmount: 0,
        salTotalAmount: 0,
        couponCnt: 0,
        canUseCoupon: 0,
        usedCoupon: 0,
        unUseCoupon: 0,
      },
      isQueryed: false,
      // 表头
      columns: [
        {
          title: '初始门店',
          align: 'center',
          dataIndex: 'departName'
        },
        {
          title: '会员姓名',
          align: 'center',
          dataIndex: 'realName'
        },
        {
          title: '会员手机',
          align: 'center',
          dataIndex: 'mobile',
         
        },
        {
          title: '可用积分',
          align: 'center',
          dataIndex: 'balance',
          scopedSlots: { customRender: 'balance' },
        },
        {
          title: '积分总数',
          align: 'center',
          dataIndex: 'totalAmount',
          scopedSlots: { customRender: 'totalAmount' },
        },
        {
          title: '核销总数',
          align: 'center',
          dataIndex: 'salTotalAmount',
          scopedSlots: { customRender: 'salTotalAmount' },
        },
        {
          title: '券投放数',
          align: 'center',
          dataIndex: 'couponCnt',
          scopedSlots: { customRender: 'couponCnt' },
        },
        {
          title: '未使用券数',
          align: 'center',
          dataIndex: 'canUseCoupon',
          scopedSlots: { customRender: 'canUseCoupon' },
        },
        {
          title: '券核销数',
          align: 'center',
          dataIndex: 'usedCoupon',
          scopedSlots: { customRender: 'usedCoupon' },
        },
        {
          title: '券过期数',
          align: 'center',
          dataIndex: 'unUseCoupon',
          scopedSlots: { customRender: 'unUseCoupon' },
        },
      ],
      orderDateRange: [],
      url: {
        list: '/report/member/memberList',
        exportXlsUrl: '/report/daily/exportXls'
      }
    }
  },
  computed: {},
  created() {
    this.init()
  },
  methods: {
    moment,
    init() {
      this.queryParam = {}
      this.loadDepartTree()
    },
    loadDepartTree() {
      queryDepartTreeList1().then(res => {
        if (res.success) {
          let departList = res.result
          if (departList.length == 1 && departList[0].orgType == 1) {
            departList = departList[0].children
          }
          this.departModel.departTreeOptions = departList

          this.departModel.departTreeOptions.forEach(x => {
            if (!x['children']) {
              x['children'] = []
            }
            let allShop = { title: '全部门店', value: '0' }
            x['children'].unshift(allShop)
          })

          // this.$set(this.queryParam,'selecteddeparts',[departList[0].id,'0'])
        }
      })
    },
    handleMemberPointsDetail(record) {
      this.assembleQueryParam()
      this.$nextTick(()=>{ this.$refs.modelFormBalanceDetail.view(record,this.queryParam)})
      this.$refs.modelFormBalanceDetail.title = '可用积分详情'
    },
    handleTotalBalanceDetail(record) {
      this.assembleQueryParam()
      this.$nextTick(()=>{ this.$refs.modelFormTotalBalanceDetail.view(record,this.queryParam)})
      this.$refs.modelFormTotalBalanceDetail.title = '总获取积分详情'
    },
    handleExpendBalanceDetail(record) {
      this.assembleQueryParam()
      this.$nextTick(()=>{ this.$refs.modelFormExpendDetail.view(record,this.queryParam)})
      this.$refs.modelFormExpendDetail.title = '积分实际消费详情'
    },
    handleMemberCouponDetail(record) {
      this.assembleQueryParam()
      this.queryParam.showAll = true
      this.queryParam.showUsed = false
      this.queryParam.showCantUse = false
      this.$nextTick(()=>{ this.$refs.modelFormGrantCouponDetail.view(record,this.queryParam)})
      this.$refs.modelFormGrantCouponDetail.title = '用户领取优惠券详情'
    },
    handleMemberunUseCouponDetail(record) {
      this.assembleQueryParam()
      this.queryParam.showAll = true
      this.queryParam.showUsed = false
      this.queryParam.showCantUse = true
      this.$nextTick(()=>{ this.$refs.modelFormGrantCouponDetail.view(record,this.queryParam)})
      this.$refs.modelFormGrantCouponDetail.title = '用户未使用优惠券'
    },
    handleMemberUsedCouponDetail(record) {
      this.assembleQueryParam()
      this.queryParam.showAll = true
      this.queryParam.showUsed = true 
      this.queryParam.showCantUse = false
      this.$nextTick(()=>{ this.$refs.modelFormGrantCouponDetail.view(record,this.queryParam)})
      this.$refs.modelFormGrantCouponDetail.title = '用户券核销数'
    },
    handleMemberunUsedCouponDetail(record) {
      this.assembleQueryParam()
      this.queryParam.showAll = false
      this.queryParam.showUsed = false
      this.queryParam.showCantUse = false
      this.$nextTick(()=>{ this.$refs.modelFormGrantCouponDetail.view(record,this.queryParam)})
      this.$refs.modelFormGrantCouponDetail.title = '用户券已过期数'
    },
    assembleQueryParam() {
      console.log("进入assembleQueryParam");
      console.log(this.queryParam.selecteddeparts);
      let selecteddeparts = this.queryParam.selecteddeparts
      if (selecteddeparts && selecteddeparts.length == 2) {
        this.queryParam.orgIds = selecteddeparts[0]
        this.queryParam.shopIds = selecteddeparts[1] == 0 ? null : selecteddeparts[1]
      } else {
        this.queryParam.orgIds = null
        this.queryParam.shopIds = null
      }
      if(!this.queryParam.orgIds){
        this.$message.warning("门店必选")
        return false
      }
      return true
    },
    searchQuery1() {

      if (!this.assembleQueryParam()) {
        return
      }
      
      this.isQueryed = true
      this.loadData(1)
    },
    loadData(arg) {
      console.log('--ipagination--', this.ipagination)
      this.loading = true
      if(this.ipagination && this.ipagination.current > 1){
        //分页查询不在多次查汇总
         
      }
      this.loadList()
     
    },
    loadList(arg){
      console.log('---loadData---')
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //获取查询条件
      this.loading = true
      getAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            console.log("dataSource 说",this.dataSource);
            if (res.result.total) {
              this.ipagination.total = res.result.total
              //总页数动态添加汇总行
              this.appendTotalRow()
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    disabledDate(current) {
      console.log('current=', current)
      return current && current > moment().subtract(1, 'days')
    },
    searchReset1() {
      this.init()
    },
    handleExportXls1(fileName) {
      if (!this.assembleQueryParam()) {
        return
      }

      this.handleExportXls(fileName)
    },
    handleExportDetailXls(fileName) {
      if (!this.checkExportParam()) {
        return
      }

      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length != 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportDetailXlsUrl, param).then(data => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    }
  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';
.sum {
  margin-right: 24px;
  .b {
    font-weight: 600;
    color: @primary-color;
  }
}
</style>